#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#ifndef __M_UTIL_H__
#define __M_UTIL_H__

using std::string;
using std::cerr;
using std::endl;
using std::cout;

namespace ad_log
{
    namespace util
    {
        class date
        {
        public: 
            static time_t currentTime()
            {
                return time(nullptr);
            }
        };

        class file
        {
        public:
            static bool isExist(const string& path)
            {
                struct stat tmp;
                if(stat(path.c_str(), &tmp) == -1)
                {
                    return false;
                }
                return true;
            }

            static string fileDirectoryPath(const string& filename)
            {
                //eg. a/b/c/e/txt
                //eg. ../txt
                if(!isExist(filename))
                {
                    return "error: no such file";
                }

                size_t pos = filename.find_last_of("/\\");
                if(pos == string::npos)
                {
                    return ".";
                }
                else
                {
                    return filename.substr(0,pos+1);
                }
            }

            // eg：(1)./a/b/c  (2)../a/b/c  (3) a/b/c (4) a
            //接口功能：创建目录，若上级目录不存在，则递归进行创建
            static bool createDirectory(const string& pathname)
            {
                int start = 0;
                while (start < pathname.size())
                {
                    int pos = pathname.find_first_of("/\\", start);
                    if(pos == string::npos)
                    {
                        if(mkdir(pathname.c_str(), 0775) == -1)
                        {
                            cerr << strerror(errno) << endl;
                            return false;
                        }
                        return true;
                    }      

                    string rootPath = pathname.substr(0,pos);    
                    if(rootPath == "." || rootPath == "..")
                    {
                        start = pos+1;
                        continue;
                    }
                    
                    if(!isExist(rootPath))
                    {
                        mkdir(rootPath.c_str(), 0775);
                    }
                    start = pos+1;
                }
            }
        };
    }
}

#endif